package com.lu.project.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lu.project.common.BaseResponse;
import com.lu.project.common.ResultUtils;
import com.lu.project.constant.UserCacheConstant;
import com.lu.project.exception.BusinessException;
import com.lu.project.exception.ErrorCode;
import com.lu.project.exception.ThrowUtils;
import com.lu.project.mapper.DeviceMapper;
import com.lu.project.mapper.MemberElderMapper;
import com.lu.project.model.dto.user.Result;
import com.lu.project.model.dto.user.UserDTO;
import com.lu.project.model.dto.user.UserLoginRequest;
import com.lu.project.model.entity.Device;
import com.lu.project.model.entity.MemberElder;
import com.lu.project.model.entity.User;
import com.lu.project.model.vo.MemberElderVo;
import com.lu.project.model.vo.UserVO;
import com.lu.project.model.vo.user.LoginUserVo;
import com.lu.project.service.MemberElderService;
import com.lu.project.service.UserService;
import com.lu.project.utils.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;


@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MemberElderMapper memberElderMapper;

    @Resource
    private DeviceMapper deviceMapper;

   /* *//**
     * 发送手机验证码
     *//*
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        //发送短信验证码并保存验证码
        return userService.sendCode(phone,session);
//        return Result.fail("功能未完成");
    }*/


    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public BaseResponse<LoginUserVo> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVo token = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(token);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public BaseResponse<Long> register(@RequestBody UserDTO userDTO) {
//        log.info("username:"+userInfo.getUsername()+"  password:"+userInfo.getPassword());
        ThrowUtils.throwIf(userDTO==null, ErrorCode.PARAMS_ERROR);
        Long id = userService.Register(userDTO);
        return ResultUtils.success(id);
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    @ApiOperation("用户登出接口")
    public BaseResponse<String> logout(){
        // 实现登出功能
        //userService.login()
        Long userId = UserThreadLocal.getUserId();
        ThrowUtils.throwIf(userId==null,ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        String key = UserCacheConstant.JWT_TOKEN +userId;
        try {
            stringRedisTemplate.delete(key);
            UserThreadLocal.remove();
        }
       catch (Exception ignored){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户没有退出成功");
       }
        return ResultUtils.success("用户退出登录成功");
    }


    @GetMapping("/me")
    @ApiOperation("获取当前登录用户")
    public BaseResponse<UserVO> me(){
        // 获取当前登录的用户并返回
        Long userId = UserThreadLocal.getUserId();
        ThrowUtils.throwIf(userId==null,ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        User user = userService.getById(userId);
        ThrowUtils.throwIf(user==null,ErrorCode.NOT_FOUND_ERROR,"当前登录用户不存在");
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        return ResultUtils.success(userVO);
    }

    @GetMapping("/elder")
    @ApiOperation("获取当前登录用户关联的老人信息")
    public BaseResponse<List<MemberElder>> getElderById(){
        // 获取当前登录的用户并返回
        Long userId = UserThreadLocal.getUserId();
        ThrowUtils.throwIf(userId==null,ErrorCode.NOT_LOGIN_ERROR,"用户未登录");
        QueryWrapper<MemberElder> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(ObjectUtil.isNotNull(userId), "member_id", userId);

        List<MemberElder> memberElders = memberElderMapper.selectList(userQueryWrapper);
        return ResultUtils.success(memberElders);
    }
    @GetMapping("/device")
    @ApiOperation("根据用户id获取绑定设备")
    public BaseResponse<List<Device>> GetDevice(Long id) {
        ThrowUtils.throwIf(id==null,ErrorCode.PARAMS_ERROR,"请求数据错误");
//        log.info("username:"+userInfo.getUsername()+"  password:"+userInfo.getPassword());
        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.eq("bind_elder_id",id);
        List<Device> devices = deviceMapper.selectList(deviceQueryWrapper);
        return ResultUtils.success(devices);
    }

    @PostMapping("/bind/device")
    @ApiOperation("为老人绑定设备")
    public BaseResponse<Long> BindDevice(String deviceName,Long elderId) {
//        log.info("username:"+userInfo.getUsername()+"  password:"+userInfo.getPassword());
        ThrowUtils.throwIf((deviceName==null||elderId==null),ErrorCode.PARAMS_ERROR);
        User byId = userService.getById(elderId);
        ThrowUtils.throwIf(byId==null,ErrorCode.PARAMS_ERROR,"当前老人信息不存在");
        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.eq("device_name",deviceName);
        Device de = deviceMapper.selectOne(deviceQueryWrapper);
        ThrowUtils.throwIf(de==null,ErrorCode.PARAMS_ERROR,"当前设备不存在");
        ThrowUtils.throwIf(de.getBindElderId()!=-1,ErrorCode.PARAMS_ERROR,"当前设备已经绑定，请先解绑");
        LambdaUpdateWrapper<Device> deviceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        deviceLambdaUpdateWrapper.eq(Device::getDeviceName,deviceName);
        deviceLambdaUpdateWrapper.set(Device::getBindElderId,elderId);
        Device device = new Device();
        device.setBindElderId(elderId);
        int update = deviceMapper.update(device, deviceLambdaUpdateWrapper);
        ThrowUtils.throwIf(update<1,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(elderId,"绑定设备成功");
    }

    @PostMapping("/nobind/device")
    @ApiOperation("为老人解绑设备")
    public BaseResponse<Long> NoBindDevice(String deviceName,Long elderId) {
//        log.info("username:"+userInfo.getUsername()+"  password:"+userInfo.getPassword());
        User byId = userService.getById(elderId);
        ThrowUtils.throwIf(byId==null,ErrorCode.PARAMS_ERROR,"当前老人信息不存在");
        ThrowUtils.throwIf((deviceName==null||elderId==null),ErrorCode.PARAMS_ERROR);
        QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
        deviceQueryWrapper.eq("device_name",deviceName);
        Device de = deviceMapper.selectOne(deviceQueryWrapper);
        ThrowUtils.throwIf(de==null,ErrorCode.PARAMS_ERROR,"当前设备不存在");
        ThrowUtils.throwIf(de.getBindElderId()==-1,ErrorCode.PARAMS_ERROR,"当前设备未绑定信息");
        ThrowUtils.throwIf(!Objects.equals(de.getBindElderId(), elderId),ErrorCode.PARAMS_ERROR,"该设备绑定人不是当前老人，不能解绑");
        LambdaUpdateWrapper<Device> deviceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        deviceLambdaUpdateWrapper.eq(Device::getDeviceName,deviceName);
        deviceLambdaUpdateWrapper.set(Device::getBindElderId,-1);
        Device device = new Device();
        device.setBindElderId(null);
        int update = deviceMapper.update(device, deviceLambdaUpdateWrapper);
        ThrowUtils.throwIf(update<1,ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(elderId,"解绑设备成功");
    }


/*    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }*/

/*    // UserController 根据id查询用户

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable("id") Long userId){
        // 查询详情
        User user = userService.getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 返回
        return Result.ok(userDTO);
    }

    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }
    @GetMapping ("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }*/
}
